package com.ferry.common.util.concurrent.rejected;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created by daiyong
 */
public class DiscardPolicy extends AbstractRejectedExecutionHandler {

	private Integer disCardSize = 100;

	public DiscardPolicy(String threadPoolName, boolean dumpNeeded, String dumpPrefixName, Integer disCardSize) {
		super(threadPoolName, dumpNeeded, dumpPrefixName);
		this.disCardSize = disCardSize;
	}

	public DiscardPolicy(String threadPoolName, boolean dumpNeeded, String dumpPrefixName) {
		super(threadPoolName, dumpNeeded, dumpPrefixName);
	}

	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

		dumpJvmInfoIfNeeded();

		//如果线程池未关闭 抛弃队列中一部分runnable 把当前runnable 放入其中
		if (!executor.isShutdown()) {
			BlockingQueue<Runnable> queue = executor.getQueue();
			for (Integer i = 0; i < disCardSize; i++) {
				queue.poll();
			}
			queue.offer(r);
		}

	}
}
